package com.program.houai.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.program.houai.entity.CmallOrderGoodsEntity;
import com.program.houai.entity.MemberCardEntity;
import com.program.houai.entity.UserVipCardEntity;
import com.program.houai.entity.VipCardOrderEntity;
import com.program.houai.mapper.VipCardOrderMapper;
import com.program.houai.pay.PayResult;
import com.program.houai.po.VipCardOrderPO;
import com.program.houai.service.IGenerateOrderNumberService;
import com.program.houai.service.IMemberCardService;
import com.program.houai.service.IUserVipCardService;
import com.program.houai.service.IVipCardOrderService;
import com.program.houai.util.DateFullUtils;
import com.program.houai.vo.SubmitOrderVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * @version v1.0
 * @ProjectName: EOrder-master
 * @ClassName: VipCardOrderServiceImpl
 * @Description: TODO(一句话描述该类的功能)
 * @Author: Topcheer
 * @Date: 2024/8/31 10:05
 */
@Service
@Slf4j
public class VipCardOrderServiceImpl extends ServiceImpl<VipCardOrderMapper, VipCardOrderEntity> implements IVipCardOrderService {

    @Autowired
    private IGenerateOrderNumberService generateOrderNumberService;

    @Autowired
    private IMemberCardService memberCardService;

    @Autowired
    private IUserVipCardService userVipCardService;

    @Value("${system.order.validityPeriod}")
    private int validityPeriod;

    @Override
    @Transactional
    public String saveVipCardOrder(SubmitOrderVO submitOrderVO,int userId) {
            MemberCardEntity memberCardEntity = memberCardService.getById(submitOrderVO.getCardId());
            String orderNUmber = generateOrderNumberService.generateOrderNumber();
            VipCardOrderEntity vipCardOrderEntity = new VipCardOrderEntity();
            vipCardOrderEntity.setUserId(userId);
            vipCardOrderEntity.setCardId(submitOrderVO.getCardId());
            vipCardOrderEntity.setTxnNo(orderNUmber);
            vipCardOrderEntity.setTxnStatus(0);
            vipCardOrderEntity.setPrice(memberCardEntity.getPrice());
            vipCardOrderEntity.setCount(submitOrderVO.getCount());
            vipCardOrderEntity.setTotalPrice(submitOrderVO.getCount() * memberCardEntity.getPrice() );
            vipCardOrderEntity.setCreateTime(new Date());
            Date endDate = DateFullUtils.addDate4Second(new Date(),validityPeriod);
            vipCardOrderEntity.setExpirationTime(endDate);
            this.baseMapper.insert(vipCardOrderEntity);
            return orderNUmber ;
    }

    @Override
    public VipCardOrderPO getOrderInfoByNumber(String txnNo) {
        VipCardOrderPO vipCardOrderPO =  this.baseMapper.getOrderInfoByNumber(txnNo);
        BigDecimal divisor = BigDecimal.valueOf(100);
        BigDecimal dividend = BigDecimal.valueOf( vipCardOrderPO.getPrice());
        BigDecimal orderPrice = dividend.divide(divisor, 2, RoundingMode.HALF_UP);
        vipCardOrderPO.setOrderPrice(orderPrice.toString());
        vipCardOrderPO.setUrl("/static/vip/"+vipCardOrderPO.getCardId()+".png");
        BigDecimal dividend1 = BigDecimal.valueOf( vipCardOrderPO.getTotalPrice());
        BigDecimal totalPrice = dividend1.divide(divisor, 2, RoundingMode.HALF_UP);
        vipCardOrderPO.setAmountPrice(totalPrice.toString());
        return vipCardOrderPO;
    }

    @Override
    public IPage<VipCardOrderPO> getOrderListByUserId(IPage page, int userId,String txnStatus) {
        return this.baseMapper.getOrderListByUserId(page,userId,txnStatus);
    }

    @Override
    @Transactional
    public boolean payBack(String txnNo, PayResult payResult) {
        QueryWrapper<VipCardOrderEntity> wrap = new QueryWrapper<VipCardOrderEntity>();
        wrap.eq("txn_no",txnNo);
        VipCardOrderEntity  vipCardOrderEntity = this.baseMapper.selectOne(wrap);
        if (vipCardOrderEntity == null){
            log.info("订单号不存在"+txnNo);
        }
        //已发货不需要再处理
        if (vipCardOrderEntity.getTxnStatus() == 2){
            log.info("已发货不需要再处理"+txnNo);
            return true;
        }
        vipCardOrderEntity.setPayType(0);
        vipCardOrderEntity.setTxnStatus(2);
        vipCardOrderEntity.setCashFee(Integer.parseInt(payResult.getCash_fee()));
        vipCardOrderEntity.setUpdateTime(new Date());
        vipCardOrderEntity.setPayTime(new Date());
        MemberCardEntity memberCardEntity = memberCardService.getById(vipCardOrderEntity.getCardId());
        Date endDate = DateFullUtils.addDate(new Date(),memberCardEntity.getValidityPeriod());
        //到期时间
        vipCardOrderEntity.setEffectiveTime(endDate);
        this.baseMapper.updateById(vipCardOrderEntity);

        List<UserVipCardEntity> carList = new ArrayList<>();
        //把卡插入到 tb_user_vip_card 表中
        for (int i= 0 ;i<vipCardOrderEntity.getCount();i++){
            UserVipCardEntity userVipCardEntity = new UserVipCardEntity();
            userVipCardEntity.setCardId(vipCardOrderEntity.getCardId());
            userVipCardEntity.setUserId(vipCardOrderEntity.getUserId());
            userVipCardEntity.setCardStatus(0);
            userVipCardEntity.setCreateTime(new Date());
            String code = UUID.randomUUID().toString().replace("-","");
            userVipCardEntity.setCardCode(code);
            userVipCardEntity.setEffectiveTime(endDate);
            carList.add(userVipCardEntity);
        }
        boolean result = userVipCardService.saveBatch(carList);
        return result;
    }
}
